//
//  XFRefreshSuperView.m
//  WorkManager
//
//  Created by ukongm on 17/1/7.
//  Copyright © 2017年 ukongm. All rights reserved.
//
#import "XFRefresh.h"
#import "XFRefreshSuperView.h"
#import "XFRefreshConst.h"
#import "XFManager.h"
#define DOWNLOADVIEW_SHOWFRAME CGRectMake((self.width - DOWNLOAD_SIZE)/2, (self.height - DOWNLOAD_SIZE)/2, DOWNLOAD_SIZE, DOWNLOAD_SIZE) //加载视图，展示的位置

/** 高度 */
static CGFloat const VIEW_HEIGHT = 40;
/** 加载视图的宽度 */
static CGFloat const LINE_SIZE = 25;
/** 加载视图的线宽 */
static CGFloat const LINE_WIDTH = 2;
/** 活动视图的宽度 */
static CGFloat const DOWNLOAD_SIZE = LINE_SIZE + 2;

@interface XFRefreshSuperView()

/** 进度 */
@property(nonatomic,strong)CAShapeLayer* progressLayer;
/** 彩环 */
@property(nonatomic,strong)XFRefreshDownloadView* downloadView;

@end

@implementation XFRefreshSuperView

- (XFRefreshDownloadView *)downloadView{
    
    if (_downloadView == nil) {
        _downloadView = [[XFRefreshDownloadView alloc] initWithFrame:DOWNLOADVIEW_SHOWFRAME andLineWidth:LINE_WIDTH];
    }
    return _downloadView;
}

-(instancetype)initWithScrollView:(UIScrollView*)scrollView{
    
    self = [super initWithFrame:CGRectZero];
    if (self) {
        self.scrollView = scrollView;
    }
    return self;
}

- (void)setScrollView:(UIScrollView *)scrollView{
    
    //释放
    if ([self freeWith:scrollView]) return;
    
    [self addKVOAndFrameWithScrollView:scrollView];
    
    _scrollView = scrollView;
}

#pragma mark - 设置关联视图之后的初始化设置
- (void)addKVOAndFrameWithScrollView:(UIScrollView*)scrollView{
    //添加之前先移除
    [_scrollView removeObserver:self forKeyPath:XFRefreshContentOffset];
    [scrollView addObserver:self forKeyPath:XFRefreshContentOffset options:NSKeyValueObservingOptionNew context:nil];
    
    self.frame = [self frameWithStyle:self.viewStyle andScrollView:scrollView];
    
    [self addAnimationView];
    
    [scrollView addSubview:self];
    
    [self setStatus:XFRefreshStatusNormal];
}

#pragma mark - 动画的展示
- (void)addAnimationView{
    
    CGFloat size = LINE_SIZE;
    
    CGRect frame = DOWNLOADVIEW_SHOWFRAME;
    
    UIBezierPath* path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, size, size)];
    
    CAShapeLayer* layer = [CAShapeLayer layer];
    layer.frame = frame;
    layer.strokeColor = [UIColor blueColor].CGColor;
    layer.fillColor = [UIColor clearColor].CGColor;
    layer.lineWidth = LINE_WIDTH;
    layer.lineCap = @"round";
    layer.strokeStart = 0;
    layer.strokeEnd = 0;
    layer.actions = @{@"strokeEnd":[NSNull new]}; // 关闭自带的动画效果
    //    layer.lineJoin = kCALineJoinBevel;
    //    layer.fillRule = kCAFillRuleEvenOdd;
    layer.path = path.CGPath;
    layer.affineTransform = CGAffineTransformMakeRotation(M_PI_2);
    
    self.progressLayer = layer;
    
    [self.layer addSublayer:layer];
    
    [self addSubview:self.downloadView];
}

#pragma mark - 进行释放（这里会出现循环引用,需要手动释放
/**
 根据scrollView的值 去确定释放还是不释放
 
 @param scrollView 视图
 
 @return 是否释放 NO 没释放
 */

- (BOOL)freeWith:(UIScrollView*)scrollView{
    
    if (!scrollView) {
        [self setStatus:XFRefreshStatusNormal];
        [self.scrollView removeObserver:self forKeyPath:XFRefreshContentOffset];
        [self removeFromSuperview];
        _scrollView = nil;
        return YES;
    }
    return NO;
}


- (void)setStatus:(XFRefreshStatus)status{
    
    if (_status == status) return;
    
    //如果之前的状态不是正在刷新，就保存contentInSet
    if (_status != XFRefreshStatusRefreshing) _scrollViewInitSet = self.scrollView.contentInset;
    
    switch (status) {
        case XFRefreshStatusNormal:
        {
            self.progressLayer.hidden = NO;
            self.progressLayer.strokeEnd = 0;
            [self.downloadView stopAnimation];
            self.progressLayer.strokeColor = [UIColor blueColor].CGColor;
            break;
        }
        case XFRefreshStatusRefreshing:
        {
            self.progressLayer.hidden = YES;
            [self.downloadView startAnimation];
            
            //优先调用block
            if (self.refreshBegin) {
                self.refreshBegin(self);
            }else{
                if (self.delegate && [self.delegate respondsToSelector:@selector(refreshBeginWithView:)]) {
                    [self.delegate refreshBeginWithView:self];
                }
            }
            break;
        }
        case XFRefreshStatusWillRefresh:
            
            break;
        case XFRefreshStatusPulling:
            self.progressLayer.strokeColor = [UIColor redColor].CGColor;
            break;
            
        default:
            break;
    }
    
    _status = status;
}

#pragma mark - KVO

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    
    //正在刷新的时候，滚蛋
    if (self.status == XFRefreshStatusRefreshing) return;
    
    
    if ([keyPath isEqualToString:XFRefreshContentOffset]) {
        
        CGPoint point = [change[@"new"] CGPointValue];
        
        if (self.viewStyle == XFRefreshViewStyleFooter) {
            point.y = (point.y + self.scrollView.height) - self.scrollView.contentSize.height;
        }
        
        [self xf_algorithmForOffset:point.y * self.viewStyle andStandard:VIEW_HEIGHT];
    }
    
}

#pragma mark - 核心算法

/**
 核心算法，动画
 
 @param offset   偏移量
 @param standard 标准值（偏移多少开始触发事件的一个标准）
 */
- (void)xf_algorithmForOffset:(CGFloat)offset andStandard:(CGFloat)standard{
    
    if (self.scrollView.isDragging) {
        CGFloat scale = (offset - 20) / standard;
        
        self.progressLayer.strokeEnd = scale;
        //手指在滚动视图上的时候
        if (scale <= 1 && self.status == XFRefreshStatusPulling) {
            [self setStatus:XFRefreshStatusNormal];
            
        }else if (scale > 1 && self.status == XFRefreshStatusNormal){
            
            [self setStatus:XFRefreshStatusPulling];
        }
        
    }else{
        //手指不在视图上的时候
        if (self.status == XFRefreshStatusPulling) {
            [self setStatus:XFRefreshStatusRefreshing];
            
        }
    }
}

#pragma mark - 自定义外部调用事件
- (void)endRefreshing{
    [self setStatus:XFRefreshStatusNormal];
}

- (void)beginRefreshing{
    if (self.window) {
        [self setStatus:XFRefreshStatusRefreshing];
    }
}

#pragma mark - 供给子类重写
- (NSInteger)viewStyle{
    return XFRefreshViewStyleSuper;
}

#pragma mark - 根据viewStyle返回该控件的位置
- (CGRect)frameWithStyle:(XFRefreshViewStyle)style andScrollView:(UIScrollView*)scrollView{
    
    CGRect frame = CGRectZero;
    switch (style) {
        case XFRefreshViewStyleSuper:
            
            break;
        case XFRefreshViewStyleHeader:
            frame = CGRectMake(0, -VIEW_HEIGHT, scrollView.width, VIEW_HEIGHT);
            break;
        case XFRefreshViewStyleFooter:
        {
            if (scrollView.contentSize.height < scrollView.height) {
                scrollView.contentSize = CGSizeMake(scrollView.contentSize.width, scrollView.height);
            }
            
            frame = CGRectMake(0, scrollView.contentSize.height, scrollView.width, VIEW_HEIGHT);
            break;
        }
            
        default:
            break;
    }
    
    return frame;
}

@end
